package com.im.linving.cloud.im;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.im.linving.apputils.MD5;
import com.im.linving.apputils.PreferencesUtil;
import com.im.linving.cloud.im.bean.Container;
import com.im.linving.cloud.im.bean.ModuleProxy;
import com.im.linving.imbll.UserBll;
import com.im.linving.imsdkbll.IMMessageBll;
import com.im.linving.imsdkbll.IMUserBll;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.ResponseCode;
import com.netease.nimlib.sdk.StatusCode;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.friend.FriendService;
import com.netease.nimlib.sdk.friend.constant.VerifyType;
import com.netease.nimlib.sdk.friend.model.AddFriendData;
import com.netease.nimlib.sdk.media.record.AudioRecorder;
import com.netease.nimlib.sdk.media.record.IAudioRecordCallback;
import com.netease.nimlib.sdk.media.record.RecordType;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.QueryDirectionEnum;
import com.netease.nimlib.sdk.msg.model.SystemMessage;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends Activity  implements ModuleProxy {
    int i = 0;
    TextView  tips ,msg_list;

    EditText name,pwd,login_name,login_pwd,msg_content,friend_id;

    Button btn_reg,btn_login,getFriends,btn_send,login_out,get_local_history,get_cloud_history,btn_add_friend;

    @BindView(R.id.btn_send_image)
    Button btn_send_image;
    @BindView(R.id.image_path)
    TextView image_path;
    private Spinner spinner;

    private List<String> aL;
    private ArrayAdapter<String> arr_adapter;

    private static final int LOAD_MESSAGE_COUNT = 20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        ButterKnife.bind(this);
        //初始化view
        initView();
        //设置按钮事件监听
        setListener();
        /**
         * 监听接收消息
         */
        recieveMsg();
        /**
         * 自动登录
         */
        if(MyApplication.loginInfo()!=null){
            LoginInfo loginInfo=MyApplication.loginInfo();
            dealLoginSuccess(loginInfo.getAccount(),loginInfo.getToken());
        }
    }

    void initView(){
        tips = (TextView) findViewById(R.id.tips);
        msg_list= (TextView) findViewById(R.id.msg_list);
        name = (EditText) findViewById(R.id.name);
        pwd = (EditText) findViewById(R.id.pwd);
        btn_reg = (Button) findViewById(R.id.btn_reg);

        friend_id= (EditText) findViewById(R.id.friend_id);
        login_name = (EditText) findViewById(R.id.login_name);
        login_pwd = (EditText) findViewById(R.id.login_pwd);
        btn_login = (Button) findViewById(R.id.btn_login);
        getFriends = (Button) findViewById(R.id.getFriends);
        msg_content = (EditText) findViewById(R.id.msg_content);
        btn_send = (Button) findViewById(R.id.btn_send);
        login_out = (Button) findViewById(R.id.login_out);
        get_local_history= (Button) findViewById(R.id.get_local_history);
        get_cloud_history= (Button) findViewById(R.id.get_cloud_history);
        btn_add_friend= (Button) findViewById(R.id.btn_add_friend);

        spinner = (Spinner) findViewById(R.id.spinner);
        aL= new ArrayList<>();
        //适配器
        arr_adapter= new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, aL);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner.setAdapter(arr_adapter);

    }

     void setListener(){
         //        tv.setOnClickListener(view -> {
//            i++;
//            testRegister();
//        });
         btn_reg.setOnClickListener(view -> {
             if(name.getText().toString().length()==0){
                 Toast.makeText(MainActivity.this, "请输入用户名", Toast.LENGTH_LONG).show();
                 return;
             }
             if(pwd.getText().toString().length()==0){
                 Toast.makeText(MainActivity.this, "请输入密码", Toast.LENGTH_LONG).show();
                 return;
             }
             register(name.getText().toString(),pwd.getText().toString());
         });

         btn_login.setOnClickListener(view -> {
             if(login_name.getText().toString().length()==0){
                 Toast.makeText(MainActivity.this, "请输入用户名", Toast.LENGTH_LONG).show();
                 return;
             }
             if(login_pwd.getText().toString().length()==0){
                 Toast.makeText(MainActivity.this, "请输入密码", Toast.LENGTH_LONG).show();
                 return;
             }
             login(login_name.getText().toString(),login_pwd.getText().toString());
         });

         //拉取好友
         getFriends.setOnClickListener(view -> {
             if(btn_login.isEnabled()){
                 Toast.makeText(MainActivity.this, "请先登录", Toast.LENGTH_LONG).show();
                return;
             }

             IMUserBll imUserBll = new IMUserBll();
             imUserBll.getFriends(accountList-> {
                 aL.clear();
                 aL.addAll(accountList);
                 Toast.makeText(MainActivity.this, "拉取好友成功！", Toast.LENGTH_LONG).show();
                 arr_adapter.notifyDataSetChanged();
             },(errCode,errMsg)->{
                 Toast.makeText(MainActivity.this, "code = " + errCode + " Msg = " + errMsg, Toast.LENGTH_LONG).show();
             });
         });

         btn_send.setOnClickListener( view -> {
             if(spinner.getSelectedItem()!=null){
                 String sendObject=spinner.getSelectedItem().toString();//接收消息的用户
                 if(sendObject.length()==0){
                     Toast.makeText(MainActivity.this, "请选择发送消息的好友！", Toast.LENGTH_LONG).show();
                     return;
                 }
                 String sendContent= msg_content.getText().toString();
                 if(sendContent.length()==0){
                     Toast.makeText(MainActivity.this, "请输入发送的内容！", Toast.LENGTH_LONG).show();
                     return;
                 }
                 IMMessageBll messageBll = new IMMessageBll();
                 messageBll.sendTextMessge(sendObject,"",sendContent,sc->{
                     Toast.makeText(MainActivity.this, "發送成功", Toast.LENGTH_LONG).show();
                     msg_content.setText("");
                 },(code,msg)->{
                     Toast.makeText(MainActivity.this, "發送失敗", Toast.LENGTH_LONG).show();
                 });
             }else{
                 Toast.makeText(MainActivity.this, "请选择发送消息的好友！", Toast.LENGTH_LONG).show();
             }

         });
         //注销
         login_out.setOnClickListener( v->{
             loginOut();
         });
         /**
          * 本地历史记录获取
          */
         get_local_history.setOnClickListener(v->{
             if(btn_login.isEnabled()){
                 Toast.makeText(MainActivity.this, "请先登录", Toast.LENGTH_LONG).show();
                 return;
             }
             if(spinner.getSelectedItem()==null){
                 Toast.makeText(MainActivity.this, "请选择好友", Toast.LENGTH_LONG).show();
                 return;
             }
             getLocalHistory();
         });
         /**
          * 添加好友
          */
         btn_add_friend.setOnClickListener( v->{
             String friendId=friend_id.getText().toString();
             if(friendId.length()>0){
                 addFriend(friendId);
             }else{
                 Toast.makeText(MainActivity.this, "请输入账号", Toast.LENGTH_LONG).show();
             }
         });
     }

    /**
     * 注销
     */
    public void loginOut(){
        NIMClient.getService(AuthService.class).logout();
        login_name.setEnabled(true);
        login_pwd.setEnabled(true);
        btn_login.setEnabled(true);
        btn_send.setEnabled(false);
        aL.clear();
        arr_adapter.notifyDataSetChanged();
        login_out.setVisibility(View.VISIBLE);
        tips.setText("注销成功");
    }

    @OnClick(R.id.btn_select_image)
    void btn_select_image(){
        Intent i = new Intent(
                Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, 201);
    }

    @OnClick(R.id.btn_send_image)
    void btn_send_image(){
        String path = image_path.getText().toString();
        try {
            File file = new File(path);
            if(file.exists()){
                String sendObject=spinner.getSelectedItem().toString();//接收消息的用户
                IMMessageBll messageBll = new IMMessageBll();
                messageBll.sendImageMessage(sendObject,"",file,"icon.png",success->{
                    Toast.makeText(MainActivity.this, "發送成功", Toast.LENGTH_LONG).show();

                },(code,err)->{
                    Toast.makeText(MainActivity.this, "發送失敗 + code + err " + code + err , Toast.LENGTH_LONG).show();
                });
            }else {
                Toast.makeText(MainActivity.this, " 文件不存在" , Toast.LENGTH_LONG).show();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    AudioRecorder recorder;
    File audioFile = null;
    long audioTime = 0;
    MyThraed thraed = null;
    @OnClick(R.id.start_audio)
    void start_audio(){
      // 初始化recorder
         recorder = new AudioRecorder(
                this,
                RecordType.AAC, // 录制音频类型（aac/amr)
                10000, // 最长录音时长，到该长度后，会自动停止录音
                callback // 录音过程回调
        );
        if (!recorder.startRecord()) {
            // 开启录音失败。

        }
        thraed = new MyThraed(true);
        new Thread(thraed).start();
    }

    @OnClick(R.id.stop_audio)
    void stop_audio(){
        if(null != recorder && recorder.isRecording()){
            recorder.completeRecord(false);
        }

        if(thraed!=null){
            thraed.setFlag(false);
        }
    }
    @BindView(R.id.send_audio)
    Button send_audio;
    class MyThraed implements Runnable{
        boolean flag ;
        int i;

        public MyThraed(boolean flag) {
            this.flag = flag;
        }

        public boolean isFlag() {
            return flag;
        }

        public void setFlag(boolean flag) {
            this.flag = flag;
        }

        @Override
        public void run() {
            while (flag){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
                runOnUiThread(() -> {
                    send_audio.setText("发送语音("+i+")");
                });
            }

        }
    }


    @OnClick(R.id.send_audio)
    void send_audio(){

        if(audioFile != null && audioFile.exists()){
            if(spinner.getSelectedItem()!=null){
                IMMessageBll imMessageBll = new IMMessageBll();
                String sendObject=spinner.getSelectedItem().toString();//接收消息的用户

                imMessageBll.sendAudioMessage(sendObject,"",audioFile,audioTime,success->{
                    Toast.makeText(MainActivity.this, "语音发送成功!", Toast.LENGTH_LONG).show();

                },(code,err)->{
                    Toast.makeText(MainActivity.this, "code = " + code + " Msg = " + err, Toast.LENGTH_LONG).show();
                });
            }else{
                Toast.makeText(MainActivity.this, "请选择发送对象!", Toast.LENGTH_LONG).show();
            }
        }
    }


    IAudioRecordCallback callback = new IAudioRecordCallback() {

        @Override
        public void onRecordReady() {
            System.out.print("onRecordReady");

        }

        @Override
        public void onRecordStart(File file, RecordType recordType) {
            System.out.print("onRecordStart");

        }

        @Override
        public void onRecordSuccess(File file, long l, RecordType recordType) {
            audioFile = file;
            audioTime = l;
            System.out.print("onRecordSuccess");

        }

        @Override
        public void onRecordFail() {
            System.out.print("onRecordFail");

        }

        @Override
        public void onRecordCancel() {
            System.out.print("onRecordCancel");
        }

        @Override
        public void onRecordReachedMaxTime(int i) {
            System.out.print("onRecordReachedMaxTime");
        }
    };


    /**
     * 注册
     * @param name
     * @param pwd
     */
    public void register(String name ,String pwd) {
        UserBll userBll = new UserBll();
        userBll.register(name, pwd, success -> {
            System.out.print("success");
            Toast.makeText(MainActivity.this, "success", Toast.LENGTH_LONG).show();
        }, (code, msg) -> {
            System.out.print("code = " + code + " Msg = " + msg);
            Toast.makeText(MainActivity.this, "code = " + code + " Msg = " + msg, Toast.LENGTH_LONG).show();
        });
    }

    /**
     * 获取本地消息聊天记录
     */
    public void getLocalHistory(){
        QueryDirectionEnum direction  = QueryDirectionEnum.QUERY_OLD;
        NIMClient.getService(MsgService.class).queryMessageListEx(anchor(), direction, LOAD_MESSAGE_COUNT, true).
                setCallback(new RequestCallbackWrapper<List<IMMessage>>() {
            @Override
            public void onResult(int code, List<IMMessage> messages, Throwable exception) {
                if (code != ResponseCode.RES_SUCCESS || exception != null) {
                    return;
                }
                StringBuffer sb = new StringBuffer();
                for (IMMessage imMessage:messages){
                    sb.append(imMessage.getContent()+" \n ");
                }
                msg_list.setText(sb.toString());
                Toast.makeText(MainActivity.this, messages.size()+"条消息记录", Toast.LENGTH_LONG).show();
            }
        });
    }

    private IMMessage anchor() {
        String sessionId= PreferencesUtil.getString(this,"sessionId");
        Container container = new Container(MainActivity.this, sessionId, SessionTypeEnum.P2P, this);
        return MessageBuilder.createEmptyMessage(container.account, container.sessionType, 0);
//        if (items.size() == 0) {
//            return anchor == null ? MessageBuilder.createEmptyMessage(container.account, container.sessionType, 0) : anchor;
//        } else {
//            int index = (direction == QueryDirectionEnum.QUERY_NEW ? items.size() - 1 : 0);
//            return items.get(index);
//        }
    }

    public void addFriend(String account){
        final VerifyType verifyType =VerifyType.DIRECT_ADD;
        NIMClient.getService(FriendService.class).addFriend(new AddFriendData(account, verifyType, null))
                .setCallback(new RequestCallback<Void>() {
                    @Override
                    public void onSuccess(Void param) {
                        Toast.makeText(MainActivity.this, "添加好友成功", Toast.LENGTH_SHORT).show();
                        friend_id.setText("");
                    }

                    @Override
                    public void onFailed(int code) {
                        Toast.makeText(MainActivity.this, "on failed:" + code, Toast
                                .LENGTH_SHORT).show();
                    }

                    @Override
                    public void onException(Throwable exception) {
                    }
                });
    }

    /**
     * 登录
     * @param name
     * @param pwd
     */
    private void login(String name ,String pwd) {
        IMUserBll imUserBll = new IMUserBll();
        imUserBll.login(name, MD5.getStringMD5(pwd), s->{
            dealLoginSuccess(name ,pwd );
        }, (errCode,errMsg)->{
            tips.setText("失败 + " + errMsg + errCode );
            System.out.print("errCode = " + errCode + " errMsg = " + errMsg);
        });
    }

    public void dealLoginSuccess(String name ,String pwd){
        System.out.print("登录成功");
        tips.setText(name+"登录成功");
        login_name.setEnabled(false);
        login_pwd.setEnabled(false);
        btn_login.setEnabled(false);
        btn_send.setEnabled(true);
        login_out.setVisibility(View.VISIBLE);
        getFriends.performClick();//登录成功，拉取好友信息
        if(name!=null && pwd!=null){
            Preferences.saveUserAccount(name);
            Preferences.saveUserToken(pwd);
        }
    }


    public void recieveMsg(){
        registerObservers(true);

        /**
         * 用户状态监听
         */
        NIMClient.getService(AuthServiceObserver.class).observeOnlineStatus(
                (Observer<StatusCode>) status -> {
                    Log.i("MainActivity", "User status changed to: " + status);
                    if (status.wontAutoLogin()) {
                        // 被踢出、账号被禁用、密码错误等情况，自动登录失败，需要返回到登录界面进行重新登录操作
                        loginOut();
                    }
                }, true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 201 && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            image_path.setText(picturePath);
        }

}
    @Override
    protected void onDestroy() {
        super.onDestroy();
        registerObservers(false);
    }

    private void registerObservers(boolean register) {
        MsgServiceObserve service = NIMClient.getService(MsgServiceObserve.class);
        service.observeReceiveMessage(incomingMessageObserver, register);
    }


    @Override
    public boolean sendMessage(IMMessage msg) {
        return false;
    }

    @Override
    public void onInputPanelExpand() {

    }

    @Override
    public void shouldCollapseInputPanel() {

    }

    @Override
    public boolean isLongClickEnabled() {
        return false;
    }


    Observer<List<IMMessage>> incomingMessageObserver = (Observer<List<IMMessage>>) messages -> {
        if (messages == null || messages.isEmpty()) {
            return;
        }
        StringBuffer sb = new StringBuffer();
        for (IMMessage imMessage:messages){
            sb.append(imMessage.getContent()+" \n ");
        }
        msg_list.setText(msg_list.getText().toString()+""+sb.toString());
        Toast.makeText(MainActivity.this, "接收到消息"+messages.size(), Toast.LENGTH_LONG).show();
    };
}
